import axios from "axios";
// import qs from 'qs';
import store from "@/store";
// eslint-disable-next-line no-unused-vars
import { paramsFilter, handleError, handleSuccess } from "./help";

// 封装 axios
const service = axios.create();
let cancel;
const promiseArr = {};

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 发起请求时，取消掉当前正在进行的相同请求
    if (promiseArr[config.url]) {
      promiseArr[config.url]();
      promiseArr[config.url] = cancel;
    } else {
      promiseArr[config.url] = cancel;
    }
    // 判断是否存在token，如果存在的话，则每个http header都加上token
    if (store.state.user.token) {
      config.headers.Authorization = `Bearer ${store.state.user.token}`;
    }
    return config;
  },
  error => Promise.reject(error)
);

// 响应拦截器即异常处理
service.interceptors.response.use(
  response => {
    console.log("response:", response);
    console.log(typeof response.data);
    /**
     * 这里错误码处理
     */
    const err = {};
    // 按需求配置 error==0 表示操作成功
    switch (response.data.code) {
      case 0:
        return response.data;
      case 10000:
        return response.data;
      // break;
      default:
        err.message = response.data.msg || "操作失败";
        return Promise.reject(err);
      // break;
    }
    // 错误处理
  },
  error => {
    /**
     * 这里网络错误处理
     */
    // 按需求配置
    const err = {};
    if (!error.response) {
      err.message = error.message;
      return Promise.reject(err);
    }
    switch (error.response.status) {
      case 400:
        err.message = "错误请求";
        break;
      case 401:
        err.message = "未授权，请重新登录";
        break;
      case 403:
        err.message = "拒绝访问";
        break;
      case 404:
        err.message = "请求错误,未找到该资源";
        break;
      case 405:
        err.message = "请求方法未允许";
        break;
      case 408:
        err.message = "请求超时";
        break;
      case 500:
        err.message = "服务器出错";
        break;
      case 501:
        err.message = "网络未实现";
        break;
      case 502:
        err.message = "网络错误";
        break;
      case 503:
        err.message = "服务不可用";
        break;
      case 504:
        err.message = "网络超时";
        break;
      case 505:
        err.message = "http版本不支持该请求";
        break;
      default:
        err.message = `连接错误${error.response.status}`;
    }
    return Promise.reject(err);
  }
);

// 让ajax携带cookie 默认 false
// service.defaults.withCredentials = true;
// 设置默认请求头
service.defaults.headers = {
  // 'X-Requested-With': 'XMLHttpRequest',
  // 'Content-Type': 'application/x-www-form-urlencoded'
};
// 请求超时时长
service.defaults.timeout = 60000;

service.defaults.baseURL = process.env.VUE_APP_API_PREFIX_URL; // 环境变量

export function request(url, options, method = "GET") {
  options = options || {};
  const { params, data, headers } = options;
  return new Promise(resolve => {
    service({
      method,
      url,
      params: paramsFilter(params),
      data: paramsFilter(data),
      headers
    })
      .then(res => {
        // handleSuccess(res.msg)
        console.log(res);
        // resolve([null, res]);
      })
      .catch(err => {
        handleError(err);
        resolve([err]);
      });
  });
}

export function requestBlob(url, options, method = "GET") {
  options = options || {};
  const { params, data, headers, responseType } = options;
  return new Promise(resolve => {
    service({
      method,
      url,
      params: paramsFilter(params),
      data: paramsFilter(data),
      headers,
      responseType
    })
      .then(res => {
        handleSuccess(res.msg);
        resolve([null, res.data]);
      })
      .catch(err => {
        handleError(err);
        resolve([err]);
      });
  });
}
